import Taro from '@tarojs/taro';
import React, { useState, useEffect } from 'react';
import { View, Text, Image, ScrollView, TouchableOpacity } from '@tarojs/components';
import { MaterialIcons } from 'taro-icons';
import './index.scss';

// 学员类型定义
export interface Student {
  id: number;
  name: string;
  avatar: string;
  phone: string;
  status: 'pending' | 'confirmed' | 'graduated';
  enrollDate: string;
  courseType: string;
}

const StudentListPage: React.FC = () => {
  const [students, setStudents] = useState<Student[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'pending' | 'confirmed' | 'graduated'>('pending');

  useEffect(() => {
    // 设置页面标题
    Taro.setNavigationBarTitle({ title: '学员列表' });
    // 加载学员数据
    loadStudentData();
  }, []);

  const loadStudentData = async () => {
    try {
      setIsLoading(true);
      // 模拟API调用，实际应该调用真实接口
      // const response = await getStudentListApi();
      
      // 模拟数据
      const mockStudents: Student[] = [
        {
          id: 1,
          name: '张三',
          avatar: 'https://via.placeholder.com/80',
          phone: '138****1234',
          status: 'pending',
          enrollDate: '2024-01-15',
          courseType: 'C1手动挡'
        },
        {
          id: 2,
          name: '李四',
          avatar: 'https://via.placeholder.com/80',
          phone: '139****5678',
          status: 'confirmed',
          enrollDate: '2024-01-10',
          courseType: 'C2自动挡'
        },
        {
          id: 3,
          name: '王五',
          avatar: 'https://via.placeholder.com/80',
          phone: '137****9012',
          status: 'confirmed',
          enrollDate: '2023-12-25',
          courseType: 'C1手动挡'
        },
        {
          id: 4,
          name: '赵六',
          avatar: 'https://via.placeholder.com/80',
          phone: '136****3456',
          status: 'graduated',
          enrollDate: '2023-10-01',
          courseType: 'C2自动挡'
        }
      ];
      
      setStudents(mockStudents);
    } catch (error) {
      console.error('加载学员列表失败:', error);
      Taro.showToast({
        title: '数据加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleConfirmStudent = async (studentId: number) => {
    try {
      Taro.showLoading({ title: '处理中...' });
      // 模拟确认学员API调用
      // const response = await confirmNewStudentApi(studentId);
      
      // 模拟成功
      setTimeout(() => {
        Taro.hideLoading();
        Taro.showToast({
          title: '确认成功',
          icon: 'success'
        });
        // 更新本地数据
        setStudents(prev => prev.map(student => 
          student.id === studentId 
            ? { ...student, status: 'confirmed' }
            : student
        ));
      }, 1000);
    } catch (error) {
      console.error('确认学员失败:', error);
      Taro.hideLoading();
      Taro.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  };

  const handleStudentDetail = (studentId: number) => {
    // 跳转到学员详情页面
    Taro.navigateTo({
      url: `/pages/student-detail/index?id=${studentId}`
    });
  };

  const filteredStudents = students.filter(student => student.status === activeTab);

  return (
    <View className="student-list-page">
      {/* 顶部标签栏 */}
      <View className="tab-bar">
        <TouchableOpacity 
          className={`tab ${activeTab === 'pending' ? 'active' : ''}`}
          onPress={() => setActiveTab('pending')}
        >
          <Text className="tab-text">待确认</Text>
        </TouchableOpacity>
        <TouchableOpacity 
          className={`tab ${activeTab === 'confirmed' ? 'active' : ''}`}
          onPress={() => setActiveTab('confirmed')}
        >
          <Text className="tab-text">已确认</Text>
        </TouchableOpacity>
        <TouchableOpacity 
          className={`tab ${activeTab === 'graduated' ? 'active' : ''}`}
          onPress={() => setActiveTab('graduated')}
        >
          <Text className="tab-text">已毕业</Text>
        </TouchableOpacity>
      </View>

      {/* 学员列表 */}
      {isLoading ? (
        <View className="loading-container">
          <Text>加载中...</Text>
        </View>
      ) : (
        <ScrollView className="student-scroll">
          {filteredStudents.length > 0 ? (
            filteredStudents.map(student => (
              <View key={student.id} className="student-item">
                <TouchableOpacity className="student-info" onPress={() => handleStudentDetail(student.id)}>
                  <Image 
                    className="student-avatar" 
                    src={student.avatar} 
                    mode="aspectFill"
                  />
                  <View className="student-details">
                    <View className="student-name-row">
                      <Text className="student-name">{student.name}</Text>
                      <View className={`status-badge ${student.status}`}>
                        <Text className="status-text">
                          {student.status === 'pending' ? '待确认' : 
                           student.status === 'confirmed' ? '学习中' : '已毕业'}
                        </Text>
                      </View>
                    </View>
                    <Text className="student-phone">{student.phone}</Text>
                    <Text className="student-course">{student.courseType}</Text>
                    <Text className="student-date">报名日期：{student.enrollDate}</Text>
                  </View>
                </TouchableOpacity>
                
                {student.status === 'pending' && (
                  <TouchableOpacity 
                    className="confirm-btn"
                    onPress={() => handleConfirmStudent(student.id)}
                  >
                    <Text className="confirm-btn-text">确认</Text>
                  </TouchableOpacity>
                )}
              </View>
            ))
          ) : (
            <View className="empty-container">
              <MaterialIcons name="account-circle" size={80} color="#ccc" />
              <Text className="empty-text">暂无学员</Text>
            </View>
          )}
        </ScrollView>
      )}
    </View>
  );
};

export default StudentListPage;